package com.itheima.controller;



import com.itheima.domain.User;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@RestController
@RequestMapping("consumer")
@DefaultProperties(defaultFallback = "defaultFailBack")
public class UserController {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

    public User defaultFailBack(){
        User user = new User();
        user.setName("Default-服务降级,默认处理!");
        return user;
    }


    @GetMapping(value = "/{id}")
//    @HystrixCommand(fallbackMethod = "failBack")
    @HystrixCommand
    public User queryById(@PathVariable(value = "id") Integer id){
//        String url = "http://localhost:18081/user/find/"+id;
//        return restTemplate.getForObject(url,User.class);

        //从server中获取服务列表
        List<ServiceInstance> instances = discoveryClient.getInstances("user-provider");
        //获取第一个服务
        ServiceInstance instance = instances.get(0);

//        String url = "http://"+instance.getHost()+":"+instance.getPort()+"/user/find/"+id;
        String url = "http://user-provider/user/find/"+id;
        return restTemplate.getForObject(url,User.class);
    }

    public User failBack(Integer id){
        User user = new User();
        user.setUsername("服务降级,默认处理");
        return user;
    }

}




